package com.ywu.application.standard.menu.service;

import com.alibaba.cloud.commons.lang.StringUtils;
import com.google.gson.Gson;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.ywu.common.result.CommonResult;
import com.ywu.application.standard.menu.constant.MenuConstant;
import com.ywu.application.standard.menu.dto.MenuDto;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import java.util.Objects;

/**
 * @ClassName MenuCheckService
 * @Description TODO
 * @Author GroundDemo
 * @Date 2024/2/26 18:57
 * @Version 1.0
 **/
@Service
public class MenuCheckService {
    private final static Logger log = LoggerFactory.getLogger(MenuCheckService.class);

    /**
    * @Author GroundDemo
    * @Description 校验meta
    * @Date 18:58 2024/2/26
    * @Param [meta]
    * @return com.ywu.common.result.CommonResult<java.lang.Object>
    **/
    public CommonResult<Object> checkMetaInfo(MenuDto menuDto) {
        try {
            // 校验meta字段是否有效
            Gson gson = new Gson();
            JsonObject jsonObject = gson.fromJson(menuDto.getMeta(), JsonObject.class);
            // title字段是否存在
            JsonElement title = jsonObject.get("title");
            if (Objects.isNull(title)) {
                return CommonResult.error().setCode(MenuConstant.META_JSON_ERROR.getCode())
                        .setErrorCode(MenuConstant.META_JSON_ERROR.getErrorCode())
                        .setMessage(MenuConstant.META_JSON_ERROR.getMessage());
            }
            // title值是否与cnName相同
            if (!StringUtils.equals(title.getAsString(), menuDto.getCnName())) {
                return CommonResult.error().setCode(MenuConstant.META_JSON_ERROR.getCode())
                        .setErrorCode(MenuConstant.META_JSON_ERROR.getErrorCode())
                        .setMessage(MenuConstant.META_JSON_ERROR.getMessage());
            }
            return null;
        } catch (Exception e) {
            return CommonResult.error().setCode(MenuConstant.META_JSON_PARSE_ERROR.getCode())
                    .setErrorCode(MenuConstant.META_JSON_PARSE_ERROR.getErrorCode())
                    .setMessage(MenuConstant.META_JSON_ERROR.getMessage());
        }
    }
}
